package cn.hp.controller.customer;

import cn.hp.util.ResponseData;
import cn.hp.service.customer.CustomerService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/customer")
public class CustomerController {
    // controller层( 获取请求 给出响应 )依赖于 service层  所以service定义短信获取方法
    @Autowired
    private CustomerService customerService ;

    //  1.用户录入手机号获取到手机短信验证码，涉及阿里云短信工具类，随机生成6位验证码  将短信验证码保存在缓存中(redis)，设置过期时间
    @ResponseBody // 返回响应体是对象 而不是一个视图
    @RequestMapping("/sendSms")
    public String sendSms( @RequestParam String phoneNumber){
        // 使用短信服务 进行发送验证码，并返回发送的验证码
        String code = customerService.smsSending(phoneNumber);
        // 进行验证码的缓存 返回项目中统一定义的响应结果类型
        ResponseData responseData = customerService.cacheVerificationCode(phoneNumber , code);
        // 返回 json字符串
        return JSON.toJSONString(responseData);
    }

    // 登录验证
    @ResponseBody
    @RequestMapping("/login")
    public String login(String phoneNumber , String code , HttpServletRequest request ){
        ResponseData responseData = customerService.login(phoneNumber , code );
        // 登录成功 添加登录用户
        if (responseData.getCode() == 200){
            request.getSession().setAttribute("customerName",phoneNumber);
        }
        return  JSON.toJSONString(responseData) ;
    }

}
